package com.fenquen.dfs.storage.heartbeat;

import com.fenquen.dfs.base.protocol.Protocol;
import com.fenquen.dfs.base.protocol.data.storage_source.req_from_storage.StorageNode;
import com.fenquen.dfs.storage.config.DFSStorageConfig;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.socket.DatagramPacket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;

@EnableScheduling
@Component
public class HeartbeatSender {

    private DFSStorageConfig dfsStorageConfig;

    private Channel channel;

    private File storageDirectory;

    @Autowired
    public HeartbeatSender(DFSStorageConfig dfsStorageConfig,
                           Channel channel) {
        this.channel = channel;
        this.dfsStorageConfig = dfsStorageConfig;
        this.storageDirectory = new File(dfsStorageConfig.storagePath);
    }

    @Scheduled(fixedDelay = 16000)
    public void send() {
        StorageNode storageNode = new StorageNode();

        storageNode.host = dfsStorageConfig.serverAddress;
        storageNode.port = dfsStorageConfig.serverPort;
        storageNode.remainingSpaceByte = storageDirectory.getFreeSpace();

        Protocol protocol = new Protocol();
        protocol.protocolType = Protocol.ProtocolType.ReqFromStorage.存储节点自身状态信息;
        protocol.dataLength = (short) storageNode.getByteLength();
        protocol.data = storageNode;

        channel.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer(protocol.getByteArr()), dfsStorageConfig.multicastAddress));
    }
}
